import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";

export const useBearStore = create(
  persist(
    (set) => ({
      bears: 0,
      color: "red",
      size: "big",
      increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
      removeAllBears: () => set({ bears: 0 }),
      updateBears: (newBears) => set({ bears: newBears }),
      getOwner: async () => {
        const response = await fetch("https://api.github.com/user/1");
        const owner = await response.json();
        console.log(owner.name);
        return owner.name;
      },
      reset: () => set({ bears: 0, color: "red", size: "big" }),
    }),
    {
      name: "bear store" /* 唯一可识别 */,
      // storage: createJSONStorage(() => localStorage), // localStorage、sessionStorage、AsyncStorage
      // partialize: state => ({bears: state.bears}) // 选取部分状态进行持久化
      partialize: (state) =>
        Object.fromEntries(
          Object.entries(state).filter(([key]) => !["size"].includes(key))
        ), // 排除size状态，其他状态进行持久化
    }
  )
);
